package lumis.portal.page.serialization;

import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.page.PageConfig;
import lumis.portal.serialization.DeserializationContext;
import lumis.portal.serialization.operation.ConfigForeignKey;
import lumis.portal.serialization.operation.IConfigPersister;

import java.util.List;

/**
 * Performs a {@link PageConfig} persistence (add or update) operation
 *
 * @version $Revision: 12759 $ $Date: 2011-04-04 18:32:34 -0300 (Mon, 04 Apr 2011) $
 * @since 4.0.11
 */
public class PageConfigPersister implements IConfigPersister
{
	private String layout;
	private List<ConfigForeignKey> foreignKeys;
	
	/**
	 * @param foreignKeys foreign keys of {@link PageConfig} object
	 * @param layout original layout of {@link PageConfig}, to be used when persisting. 
	 */
	public PageConfigPersister(List<ConfigForeignKey> foreignKeys, String layout)
	{
		super();
		this.layout = layout;
		this.foreignKeys = foreignKeys;
	}

	public boolean persistConfig(DeserializationContext deserializationContext, Object config, boolean firstPersistence) throws PortalException
	{
		boolean persisted = false;

		PageConfig pageConfig = (PageConfig)config;

		if (!firstPersistence)
			pageConfig.setLayout(layout);

		// apply foreign key id mappings and analyze dependencies
		PageDependencyAnalyzer dependencyAnalyzer = new PageDependencyAnalyzer(deserializationContext, foreignKeys, pageConfig);
		if (dependencyAnalyzer.foreignKeysExists())
		{
			// apply layout foreign key id mappings
			PageLayoutUtil.applyIdMappings(deserializationContext, pageConfig);
			
			// add or update config
			PageConfig mappedPersistableConfig = dependencyAnalyzer.getMappedPersistableConfig();
			if (!mappedPersistableConfig.isAutomaticFriendlyId()
					&& mappedPersistableConfig.getFriendlyId() == null)
				mappedPersistableConfig.setAutomaticFriendlyId(true);
			if (deserializationContext.isUpdateIfElementExists() || !firstPersistence)
			{
				deserializationContext.logDebug("Adding/updating page config:", pageConfig);
				ManagerFactory.getPageManager().addOrUpdate(deserializationContext.getSessionConfig(), mappedPersistableConfig, deserializationContext.getTransaction());
			}
			else
			{
				deserializationContext.logDebug("Adding page config:", pageConfig);
				ManagerFactory.getPageManager().add(deserializationContext.getSessionConfig(), mappedPersistableConfig, deserializationContext.getTransaction());
			}
			persisted = true;
		}	
		
		return persisted;
	}
}
